package com.wang

import java.net.InetSocketAddress
import java.nio.ByteBuffer
import java.nio.channels.SelectionKey
import java.nio.channels.Selector
import java.nio.channels.SocketChannel


fun main() {
    val selector = Selector.open()
    //第1步 建立通道，此时并未连接网络
    //open接口创建的Channel并没有进行连接网络，需要使用connect接口
    val socketChannel = SocketChannel.open();

    //第2步 设置SocketChannel的阻塞模式，这里是阻塞模式
    //socketChannel默认阻塞，可以不设置
    socketChannel.configureBlocking(true);
    socketChannel.connect(InetSocketAddress("www.baidu.com", 80));

    println(socketChannel.isConnected)
    val stringBuffer = StringBuffer();
    stringBuffer.append("GET / HTTP/1.1\r\n");
    stringBuffer.append("Host: www.baidu.com\r\n");
    stringBuffer.append("\r\n");
    //\r\n\r\n表示HTTP头部结束
    //将数据写进写入通道的缓冲区
    val writeBuffer = ByteBuffer.wrap(stringBuffer.toString().toByteArray());
    //将写入通道缓冲区中的数据写入通道
    while (writeBuffer.hasRemaining()) {
        socketChannel.write(writeBuffer);
    }
    //清空准备写入通道的缓冲区
    writeBuffer.clear();
    //第3步 建立连接，这里请求百度的80端口
    //此时才真正的连上网络
    //阻塞模式，此时线程会阻塞，直到连接成功或者失败

    socketChannel.configureBlocking(false)
    socketChannel.register(selector,  SelectionKey.OP_READ)
    var i = 0;
    while (selector.select() != 0) {
        i++;
        for (key in selector.selectedKeys()) {
            println(key.readyOps())
            val channel = key.channel() as SocketChannel;
                val readBuffer = ByteBuffer.allocate(1024);
                val result = StringBuffer();
                var read = socketChannel.read(readBuffer);
                while (read > 0) {
                    result.append(String(readBuffer.array(), 0, read, Charsets.UTF_8));
                    // 清空缓冲区,继续写入
                    readBuffer.clear();
                    //当socketChannel没有数据时，线程阻塞
                    read = channel.read(readBuffer);
                }
            println(result)
                println("##########最后的结果\n");
        }
    }
    println("asd" +  i)
}